﻿using Dapper.Extensions;
using System;
using System.Web.Mvc;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;
using YouWei.Infrastructure.Service;
using YouWei.Op.Common;
using YouWei.Utility;
using YouWei.Utility.Logging;
using System.Linq;
using System.Collections.Generic;

namespace YouWei.Op.Controllers
{
    public class GroupCommentController : BaseController
    {
        private GroupCommentService _serviceComment = new GroupCommentService();
        private GroupCommentDetailService _serviceCommentDetail = new GroupCommentDetailService();
        private GroupCommentImageService _serviceCommentImage = new GroupCommentImageService();
        private UserInfoService _serviceUser = new UserInfoService();
        private TrailCommentService _serviceTrail = new TrailCommentService();
        private CarGroupService _carGroupService = new CarGroupService();

        /// <summary>
        /// 群空间评论列表
        /// </summary>
        /// <returns></returns>
        public  ActionResult GroupCommentTrailList()
        {
            return View();
        }

        /// <summary>
        /// 获取当前群空间内容的评论
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult TrailList()
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            int cid = GetParam<int>("groupCommentId");
            Page<TrailCommentDto> page = _serviceTrail.Pages(pageIndex, pageSize, cid, 0);
            return ReturnResult(page);
        }
        /// <summary>
        /// 评论列表，不筛选文章
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult TrailListAll()
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            int isShow = GetParam<int>("isShow");
            Page<TrailCommentDto> page = _serviceTrail.PagesAll(pageIndex, pageSize, isShow);
            return ReturnResult(page);
        }
        public ActionResult GroupCommentIndex()
        {
            return View();
        }

        [HttpPost]
        public PartialViewResult GroupCommentParList(GroupCommentSearchModel model)
        {
            try
            {
                var pageIndex = Convert.ToInt32(GetParam("page"));
                var pageSize = GetPageSize();
                var page = _serviceComment.Pages(pageIndex, pageSize, model);
                ViewBag.Total = page.total;
                ViewBag.PageIndex = pageIndex;
                ViewBag.PageSize = pageSize;
                return PartialView(page.rows);
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                return PartialView();
            }
        }
        public ActionResult SetTrailCommentIsShow(TrailComment comment)
        {
            var result = ResultData<int>.Error("");
            if (comment.TrailCommentID <= 0)
            {
                result.message = "缺少必要的参数TrailCommentID";
            }
            var model = _serviceTrail.Single(comment.TrailCommentID);
            if (model == null)
            {
                result.message = "TrailCommentID不正确";
            }
            model.IsShow = comment.IsShow;
            var res = _serviceTrail.Update(model);
            if (res == false)
            {
                result.message = "更新失败";
            }
            else
            {
                result.status = 0;
                result.message = "更新成功";
            }
            return ReturnResult(result);
        }

        public ActionResult GroupCommentInfo()
        {
            var id = Convert.ToInt32(GetParam("id"));
            var model = _serviceComment.GetGroupCommentInfoById(id);
            if (model != null)
            {
                if (!string.IsNullOrWhiteSpace(model.HeadImgUrl))
                {
                    var resuqes = ControllerContext.HttpContext.Request;
                    model.HeadImgUrl = Request.ApplicationPath + model.HeadImgUrl;
                }
                else
                {
                    model.HeadImgUrl = "";
                }
                var user = _serviceUser.SingleOrDefault(model.UserID);
                ViewBag.GroupCommentImages = Request.ApplicationPath + _serviceCommentImage.PagesByCommentID(id);
                ViewBag.UserName = user.UserName;
            }
            else
            {
                model = new GroupCommentDto();
            }
            return View(model);
        }

        /// <summary>
        /// 添加群空间发布
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AddComment(int id)
        {
            ViewBag.CarGroups = _carGroupService.QueryAll().Where(t => t.IsActive > 0).ToList();
            //GroupCommentDto dto;
            //if (id > 0)
            //{
            //    dto = _serviceComment.GetGroupCommentInfoById(id);
            //    dto.CommentImgs= _serviceCommentImage.PagesByCommentID(id);
            //}
            //else
            //{
            //    dto = new GroupCommentDto();
            //    dto.CommentImgs = new List<GroupCommentImage>();
            //}
            return View();
        }
        /// <summary>
        /// 设置热门
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpdateCommentIsHot()
        {
            ResultData<int> rt = ResultData<int>.Error("");
            var id = GetParam<int>("id");
            var isHot = GetParam("isHot");
            if (string.IsNullOrWhiteSpace(isHot) || id <= 0)
            {
                rt.message = "缺少必要的参数";
                return ReturnResult(rt);
            }
            var entity = _serviceComment.Single(id);
            if (entity != null)
            {
                entity.IsHot = Convert.ToInt32(isHot);
                entity.UpdateDate = DateTime.Now;
                var res = _serviceComment.Update(entity);
                if (res)
                    rt.status = 0;
                else
                    rt.message = "修改失败";
            }
            else
            {
                rt.message = "id不正确，内容不存在";
            }
            return ReturnResult(rt);
        }
        /// <summary>
        /// 添加群空间发布
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CommentSave(GroupCommentDto entity)
        {
            ResultData<int> result = new ResultData<int>();
            if (entity.GroupCommentID > 0)
            {
                entity = _serviceComment.GetGroupCommentInfoById(entity.GroupCommentID);
                entity.UpdateDate = DateTime.Now;
            }
            else
            {
                entity.CreateDate = DateTime.Now;
                entity.UpdateDate = DefaultTime;
            }
            if (entity.CommentImgs != null)
            {
                entity.EvaluateCount = entity.CommentImgs.Count;
            }

            entity.IsActvie = 1;
            entity.IsShow = 1;
            entity.IsHot = 1;


            if (string.IsNullOrEmpty(entity.CommentDesc))
            {
                if (!string.IsNullOrEmpty(entity.Detail))
                {
                    int lgh = entity.Detail.Length > 45 ? 45 : entity.Detail.Length;
                    entity.CommentDesc = entity.Detail.Substring(0, lgh);
                }
            }
            if (entity.GroupCommentID > 0)
            {
                result.data = EConvert.ToInt(_serviceComment.Update(entity));
            }
            else
            {
                //置顶之前，判断浏览量和点赞量小于50则随机50-300
                entity.PageViews = entity.EvaluateCount < 50 ? new Random().Next(50, 300) : entity.PageViews;
                entity.PraiseCount = entity.PraiseCount < 50 ? new Random().Next(50, 300) : entity.PraiseCount;
                //添加随机用户
                var user = _serviceUser.GetUserInfoRandom();
                entity.UserID = user == null ? 0 : user.UserID;

                result.data = EConvert.ToInt(_serviceComment.Insert(entity));
                var dentity = new GroupCommentDetail()
                {
                    GroupCommentID = result.data,
                    CreateDate = DateTime.Now,
                    Detail = entity.Detail,
                    UpdateDate = DefaultTime
                };
                _serviceCommentDetail.Insert(dentity);
            }


            if (entity.CommentImgs != null)
            {
                if (entity.CommentImgs.Count > 0)
                {
                    foreach (var item in entity.CommentImgs)
                    {
                        item.GroupCommentID = result.data;
                        item.CreateDate = DateTime.Now;
                        item.UpdateDate = DefaultTime;
                        item.IsActvie = 1;
                    }
                    _serviceCommentImage.Insert(entity.CommentImgs);
                }
            }

            if (entity.Comments != null)
            {
                if (entity.Comments.Count > 0)
                {
                    for (int i = 0; i < entity.Comments.Count; i++)
                    {
                        //添加随机用户
                        var user = _serviceUser.GetUserInfoRandom();
                        int usrId = user == null ? 0 : user.UserID;

                        _serviceTrail.Insert(new TrailComment()
                        {
                            Comment = entity.Comments[i],
                            CreateDate = DateTime.Now.AddMinutes(i * 10 + 10),
                            TrailIdentity = result.data,
                            UserID = usrId,
                            IsShow = 1
                        });
                    }
                }
            }

            return ReturnResult(result);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CommentDelete()
        {
            ResultData<int> rt = ResultData<int>.Error("");
            var id = GetParam<int>("id");
            if (id <= 0)
            {
                rt.message = "缺少必要的参数";
                return ReturnResult(rt);
            }
            var entity = _serviceComment.Single(id);
            if (entity != null)
            {
                entity.IsActvie = 0;
                entity.UpdateDate = DateTime.Now;
                var res = _serviceComment.Update(entity);
                if (res)
                    rt.status = 0;
                else
                    rt.message = "删除成功";
            }
            else
            {
                rt.message = "id不正确，内容不存在";
            }
            return ReturnResult(rt);
        }
    }
}